package com.tticar.invmanager.common.generator;

import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yandou on 2018/7/1.
 */
public class FreemarkerEngine {

    private String baseDir = "/Users/yandou/java/workspace/invmanager";

    private Map objectMap;
    private String templatePath = "/templates/temp/dict_codes.java.ftl";
    private String outputFile = baseDir + "/src/main/java/com/tticar/invmanager/entity/vo/DictCodes.java";

    public static FreemarkerEngine getInstance() {
        return new FreemarkerEngine();
    }

    public FreemarkerEngine() {
        this.objectMap = new HashMap();
    }

    public FreemarkerEngine put(Object key, Object value) {
        this.objectMap.put(key, value);
        return this;
    }

    public void writer() {
        Configuration configuration = new Configuration(new Version("2.3.8"));
        configuration.setDefaultEncoding(ConstVal.UTF8);
        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/");
        try {
            Template template = configuration.getTemplate(templatePath);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(outputFile));
            template.process(objectMap, new OutputStreamWriter(fileOutputStream, ConstVal.UTF8));
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map getObjectMap() {
        return objectMap;
    }

    public void setObjectMap(Map objectMap) {
        this.objectMap = objectMap;
    }
}
